﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	LanScanning
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/3/20 11:45:43
//========================================
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;

namespace SFJDService
{
    public class LanScanning
    {
        List<string> activeHosts = new List<string>(10);
        int port;
        int maxThread = 10;
        int runningThreadCount = 0;
        int scannedCount = 0;

        public LanScanning(int port)
        {
            this.port = port;
            Runtime.Printf("       开始扫描端口");
            ScanningAllHosts();
            Runtime.Printf("       端口扫描完毕");
        }

        private void ScanningAllHosts()
        {
            string m_Ip = Runtime.myIP;
            string ip_Segment = m_Ip.Remove(m_Ip.LastIndexOf('.'));
            for (int i = 1; i < 255; i++)
            {
                new Thread(() =>
                {
                    string ip = ip_Segment + '.' + i.ToString();
                    ScanningOneHost(ip);
                }).Start();
                runningThreadCount++;
                Thread.Sleep(10);
                while (runningThreadCount >= maxThread) ;//当线程数等于最大线程数时等待某一线程结束，然后进行下一线程，推拉门技术
            }
            while (scannedCount + 1 < 254) ;//等待所有线程处理完
        }

        private void ScanningOneHost(string ip)
        {
            TcpClient tcp = new TcpClient();
            IAsyncResult async = tcp.BeginConnect(ip, port, new AsyncCallback(ConnectCallBack), tcp);
            if (!async.AsyncWaitHandle.WaitOne(3000))
            {
                async.AsyncWaitHandle.Close();
            }
            runningThreadCount--;
            scannedCount++;
        }

        private void ConnectCallBack(IAsyncResult ar)
        {
            TcpClient tcp = null;
            try
            {
                tcp = ar.AsyncState as TcpClient;
                tcp.EndConnect(ar);
                //Runtime.Printf("222222222  " + tcp.Client.RemoteEndPoint.ToString().Split(':')[0]);
                activeHosts.Add(tcp.Client.RemoteEndPoint.ToString().Split(':')[0]);
                //Runtime.Printf("222211111111ccccccccccccc  " + tcp.Client.RemoteEndPoint);
                //if (tcp.Client != null)
                //{
                //    if (tcp.Connected)
                //    {
                //        Runtime.Printf("2222  " + tcp.Client.RemoteEndPoint);
                //    }
                //    tcp.EndConnect(ar);
                //    Runtime.Printf(tcp.Client.LocalEndPoint.ToString().Split(':')[0]);
                //}
            }
            catch
            {
                ;
            }
            finally
            {
                tcp.Close();
            }
        }

        public List<string> GetActiveHosts()
        {
            Runtime.Printf("  端口扫描共找到用户个数：" + activeHosts.Count);
            return activeHosts;
        }
    }
}